package com.hkpickup.notisfication;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.WebContent;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Reminder.Method;
import com.google.gdata.util.ServiceException;
/**
 * To send SMS in 1 min
 * 
 * @param title Sms message
 * @param content Event content
 * 
 */
public class SimpleSmsServlet extends HttpServlet {
	 // The base URL for a user's calendar metafeed (needs a username appended).
	  private static final String METAFEED_URL_BASE = 
	      "https://www.google.com/calendar/feeds/";

	  // The string to add to the user's metafeedUrl to access the event feed for
	  // their primary calendar.
	  private static final String EVENT_FEED_URL_SUFFIX = "/private/full";

	  // The URL for the metafeed of the specified user.
	  // (e.g. http://www.google.com/feeds/calendar/jdoe@gmail.com)
	  private static URL metafeedUrl = null;

	  // The URL for the event feed of the specified user's primary calendar.
	  // (e.g. http://www.googe.com/feeds/calendar/jdoe@gmail.com/private/full)
	  private static URL eventFeedUrl = null;
	
	
	  private static com.hkpickup.config.Common config = new com.hkpickup.config.Common();
	  
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {			
    	String title = req.getParameter("title");
    	String content = req.getParameter("content");
    	if (title==null){
    		return;
    	}
    	
		CalendarService myService = new CalendarService("sms alert");
		
	    String userName = config.getgAccountName();
	    String userPassword = config.getgSimpleSmsPassword();
	    String calName = config.getgSmsCalendarAddr();
	    
	    int output = 0;
	    
	    try {
	      metafeedUrl = new URL(METAFEED_URL_BASE + calName);
	      eventFeedUrl = new URL(METAFEED_URL_BASE + calName
	          + EVENT_FEED_URL_SUFFIX);
	 
	    } catch (MalformedURLException e) {
	      // Bad URL
	      System.err.println("MalformedURLException");
	      e.printStackTrace();
	      return;
	    }
		
	    try {	    	
	        myService.setUserCredentials(userName, userPassword);
	        // Demonstrate creating a single-occurrence event.
	        CalendarEventEntry singleEvent = createSingleEvent(myService, title, content);
//	        System.out.println("Successfully created event "
//	            + singleEvent.getTitle().getPlainText());
	        output=1;
	        
	      } catch (IOException e) {
	        // Communications error
	    	  resp.getWriter().print("IOException");
	        e.printStackTrace();
	        return;
	      } catch (ServiceException e) {
	        // Server side error
	    	  resp.getWriter().print("ServiceException");
	        e.printStackTrace();
	        return;
	      }		
	      resp.getWriter().print(output);
	}	// end doGet()
	
	  /**
	   * Creates a single-occurrence event.
	   * 
	   * @param service An authenticated CalendarService object.
	   * @param eventTitle Title of the event to create.
	   * @param eventContent Text content of the event to create.
	   * @return The newly-created CalendarEventEntry.
	   * @throws ServiceException If the service is unable to handle the request.
	   * @throws IOException Error communicating with the server.
	   */
	  private  CalendarEventEntry createSingleEvent(CalendarService service,
	      String eventTitle, String eventContent) throws ServiceException,
	      IOException {
	    return createEvent(service, eventTitle, eventContent, false, null);
	  }
	
	  /**
	   * Helper method to create either single-instance or recurring events. For
	   * simplicity, some values that might normally be passed as parameters (such
	   * as author name, email, etc.) are hard-coded.
	   * 
	   * @param service An authenticated CalendarService object.
	   * @param eventTitle Title of the event to create.
	   * @param eventContent Text content of the event to create.
	   * @param isQuickAdd True if eventContent should be interpreted as the text of
	   *        a quick add event.
	   * @param wc A WebContent object, or null if this is not a web content event.
	   * @return The newly-created CalendarEventEntry.
	   * @throws ServiceException If the service is unable to handle the request.
	   * @throws IOException Error communicating with the server.
	   */
	  private  CalendarEventEntry createEvent(CalendarService service,
	      String eventTitle, String eventContent, 
	      boolean isQuickAdd, WebContent wc) throws ServiceException, IOException {
	    CalendarEventEntry myEntry = new CalendarEventEntry();

	    myEntry.setTitle(new PlainTextConstruct(eventTitle));
	    myEntry.setContent(new PlainTextConstruct(eventContent));
	    myEntry.setQuickAdd(isQuickAdd);
	    myEntry.setWebContent(wc);

	    // Create start time and end time
      Calendar calendar = new GregorianCalendar();			// get a calendar object 
      calendar.add(Calendar.MINUTE, 2);					// Tune 
      DateTime startTime = new DateTime(calendar.getTime(), TimeZone.getDefault());

//      calendar.add(Calendar.MINUTE, 2);
//      DateTime endTime = new DateTime(calendar.getTime(), TimeZone.getDefault());
      // Add to event entry
      When eventTimes = new When();
      eventTimes.setStartTime(startTime);
      eventTimes.setEndTime(startTime);
      myEntry.addTime(eventTimes);
      // Enable SMS reminder 
      myEntry = addReminder(myEntry, 1, Method.SMS);

//      List<Reminder> reminder = myEntry.getReminder();
//      System.out.println("reminder size: "+ reminder.size());
      // Update to google
	    return service.insert(eventFeedUrl, myEntry);
	  }
	  
	  
	  /**
	   * Adds a reminder to a calendar event.
	   * 
	   * @param entry The event to update.
	   * @param numMinutes Reminder time, in minutes.
	   * @param methodType Method of notification (e.g. email, alert, sms).
	   * @return The updated EventEntry object.
	   * @throws ServiceException If the service is unable to handle the request.
	   * @throws IOException Error communicating with the server.
	   */
	  private  CalendarEventEntry addReminder(CalendarEventEntry entry,
	      int numMinutes, Method methodType) throws ServiceException, IOException {
	    Reminder reminder = new Reminder();
	    reminder.setMinutes(numMinutes);
	    reminder.setMethod(methodType);
	    entry.getReminder().add(reminder);
	   
	    //return entry.update();
	    return entry;
	  }
	  
	 
}
